package com.Jshop.auth.controller;

import com.Jshop.auth.service.AuthService;
import com.Jshop.auth.utils.JwtUtils;
import com.Jshop.auth.config.JwtProperties;
import com.Jshop.auth.entity.UserInfo;
import com.Jshop.common.utils.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

@RestController
//@EnableConfigurationProperties注解的作用是：使使用 @ConfigurationProperties 注解的类生效。
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties prop;

    /**
     * 登录并授权 验证用户名和密码 成功返回token
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response
    ){
        //登录校验并返回jwt的token
        String token = this.authService.authentication(username,password);
        //即得到的是null，数据库查无此人
        if (StringUtils.isBlank(token)){
            //得不到token，授权不通过
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        //将token写入客户端cookie,并指定httpOnly为true,防止通过js获取和修改
        CookieUtils.setCookie
                (request,response,prop.getCookieName(),token,prop.getCookieMaxAge(),null,true);

        return ResponseEntity.ok().build();
    }


    /**
     * 解析token
     * 只要有操作就会一直verify 无操作30min后token失效
     * @CookieValue("LY_TOKEN") 获取请求中的cokie中key为"LY_TOKEN"的值
     * */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(
            @CookieValue("LY_TOKEN") String token,
    HttpServletRequest request, HttpServletResponse response){
        try {
            //从token中解析token信息 获取token中的用户信息
            //利用公钥解析
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.prop.getPublicKey());
            //解析成功 重新刷新token 并刷新token有效时间
            token  = JwtUtils.generateToken(userInfo, this.prop.getPrivateKey(), this.prop.getExpire());
            System.out.println(token + LocalDateTime.now().toString());
            //更新cookie中的token
            CookieUtils.setCookie(request,response,this.prop.getCookieName(),token,this.prop.getCookieMaxAge());
            return  ResponseEntity.ok(userInfo);
        }catch (Exception e){
            e.printStackTrace();
        }
        //出现异常，响应500
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

}